package com.one2manycall.controller;

import com.one2manycall.service.UserServiceI;
import com.one2manycall.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理
 */
@Controller
@RequestMapping("/UserController")
public class UserController {

    @Autowired
    private UserServiceI userService;


    //// 页面部分 开始  /////////////////////////////////////
    @GetMapping("/users")
    public String listRoles(Model model) {
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        return "html/user/users";
    }

    @GetMapping("/users/new")
    public String createRoleForm(Model model) {
        User user = new User();
        model.addAttribute("user", user);
        return "html/user/create_user";
    }


    @GetMapping("/users/edit/{id}")
    public String editRoleForm(@PathVariable Long id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "html/user/edit_user";
    }

    //// 页面部分 结束  /////////////////////////////////////


    @PostMapping("/users/save")
    public String saveRole(@ModelAttribute("user") User user) {

        user.setPassword("123456");
        userService.saveUser(user);
        return "redirect:/UserController/users";
    }



    @PostMapping("/users/{id}")
    public String updateRole(@PathVariable Long id, @ModelAttribute("user") User user, Model model) {

        User existingUser = userService.getUserById(id);

        existingUser.setUserName(user.getUserName());

        userService.saveUser(existingUser);
        return "redirect:/UserController/users";
    }

    @GetMapping("/users/{id}")
    public String deleteRole(@PathVariable Long id) {
        userService.deleteUser(id);
        return "redirect:/UserController/users";
    }


}